<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <!-- <script src="../node_modules/vue/dist/vue.global.js"></script> -->
    <!-- 将reactive 以及effect封装在此处 -->
    <script src="./common.js"></script>
  </head>
  <body>
    <div id="app"></div>
    <script>
      const { reactive, effect } = Vue1
      class ComputedRefImpl {
        constructor(getter, setter) {
          this.getter = getter
          this.setter = setter

          this._value = undefined
          this.deps = new Set()
          this._dirty = true
          this.__v_isRef = true

          this.effect = new ReactiveEffect(getter, () => {
            if (!this._dirty) {
              this._dirty = true

              // 触发依赖
              triggerEffect(this.deps)
            }
          })
        }

        get value() {
          // 进行依赖收集
          trackEffect(this.deps)
          if (this._dirty) {
            this._value = this.effect.run()
            this._dirty = false
          }
          return this._value
        }

        set value(newValue) {
          this.setter(newValue)
        }
      }

      const computed = (getterOrOptions) => {
        let getter
        let setter

        if (isFunction(getterOrOptions)) {
          getter = getterOrOptions
          setter = Function.prototype
        } else {
          getter = getterOrOptions.get
          setter = getterOrOptions.set
        }

        const res = new ComputedRefImpl(getter, setter)

        return res
      }

      const data = { name: 'lihh', age: 20 }
      const state = reactive(data)

      const newAge = computed(() => state.age)

      effect(() => {
        document.getElementById('app').innerHTML = `我叫${state.name}, 我今年${newAge.value}岁了`
      })

      setTimeout(() => {
        state.age++
      }, 4000)
    </script>
  </body>
</html>
